from loguru import logger
from db_tools import MysqlTool
from tools.base_tools import generate_date_range
import pandas as pd
from tools.base_tools import fetch_data
from pandas import DataFrame


class PushData:
    def __init__(self, start_date, end_date, table_name):
        self.day_list = generate_date_range(start_date, end_date)
        self.table_name = table_name

    def get_many_days_data(self):
        df_all = pd.DataFrame()
        for day_str in self.day_list:
            df_one_day = self.get_one_day_data(day_str)
            df_all = pd.concat([df_all, df_one_day], ignore_index=True)
        return df_all

    # 只需要重写这个逻辑就可以了
    def get_one_day_data(self, day_str) -> pd.DataFrame:
        return pd.DataFrame()

    def pipei(self, df_orders):
        return df_orders

    def push_mysql(self):
        df_orders = self.get_many_days_data()
        if not len(df_orders):
            logger.warning("无需匹配")
            return
        # 其他的匹配逻辑
        df_orders = self.pipei(df_orders)
        # logger.debug(len(df_orders))
        try:
            with MysqlTool() as db_tool:
                db_tool.upsert_df(df_orders, self.table_name)
                logger.success(
                    f"pushed {len(df_orders)} orders to mysql,{self.table_name}"
                )
                return True
        except Exception as e:
            logger.error(f"push mysql error: {e}")
            return False

    def push_mongo(self):
        pass


def get_df_in_type():
    url_in_type = "https://scapi.tayunapi.com/funcLog/conf?type=1"
    in_type_data = fetch_data(url_in_type)
    df_in_type = DataFrame(in_type_data)
    return df_in_type
